<?php
namespace Home\Controller;
use Think\Controller;

class UserwxregisterController extends  BaseController
{
    public function __construct()
    {
        parent::__construct();

    }
	public function index(){


        $openid_exist['wx_user_openid'] = \es_session::get('wx_user_openid');
        $openid_exist['openid'] = \es_session::get('wx_user_openid');
        $openid_exist['nickname'] = \es_session::get('nickname');
        $openid_exist['headimgurl'] = \es_session::get('headimgurl');
        $openid_exist['country'] = \es_session::get('country');
        $openid_exist['sex'] = \es_session::get('sex');
        $openid_exist['language'] = \es_session::get('language');
        $openid_exist['city'] = \es_session::get('city');
        $openid_exist['province'] = \es_session::get('province');
		if(empty($openid_exist['wx_user_openid']) ) {
            //		$user =  $GLOBALS['user_info'];
            //		$root['session_id'] =\es_session::id();
            //		$id = intval($GLOBALS['request']['id']);//商品ID
            //		$city_name =strim($GLOBALS['request']['city_name']);//城市名称
            //		$user_id = intval($user['id']);
            $code = ($_GET['code']);
            $from = isset($_GET['r']) ? $_GET['r'] : 0;
            if($from){
                $redirect_uri = 'http%3a%2f%2fwap.yzlicai.com%2findex.php%3fm%3dHome%26c%3dUserwxregister%26a%3dindex%26r%3'.$from;
            }else{
                $redirect_uri = 'http%3a%2f%2fwap.yzlicai.com%2findex.php%3fm%3dHome%26c%3dUserwxregister%26a%3dindex';
            }

            if ($code) {
                $access_token_url = "https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=" . $redirect_uri . "&appid=wx4a6d0b9fa17894ce&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
                $appid = "wx4a6d0b9fa17894ce";
                $secret = "62c719b3a7d09b73aef0a64a6197e0c5";
                $from = isset($_GET['r']) ? $_GET['r'] : 0;
                $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $get_token_url);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                $res = curl_exec($ch);
                curl_close($ch);
                $json_obj = json_decode($res, true);

                //根据openid和access_token查询用户信息
                $access_token = $json_obj['access_token'];
                $openid = $json_obj['openid'];
                $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $get_user_info_url);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                $res = curl_exec($ch);
                curl_close($ch);

                //解析json
                $user_obj = json_decode($res, true);
                if(empty($user_obj['errcode']) && $user_obj['openid']  ){
                    \es_session::set('wx_user_openid',$user_obj['openid']);
                    \es_session::set('nickname',$user_obj['nickname']);
                    \es_session::set('headimgurl',$user_obj['headimgurl']);
                    \es_session::set('country',$user_obj['country']);
                    \es_session::set('sex',$user_obj['sex']);
                    \es_session::set('language',$user_obj['language']);
                    \es_session::set('city',$user_obj['city']);
                    \es_session::set('province',$user_obj['province']);
                    \es_session::set('from_who',$from);
                    $weixin_data['openid'] = $openId = $user_obj['openid'];
                    $weixin_data['nickname'] = $nickname = $user_obj['nickname'];
                    $weixin_data['headimgurl'] = $headimgurl = $user_obj['headimgurl'];
                    $weixin_data['city'] = $user_obj['city'];
                    $weixin_data['sex'] = $user_obj['sex'];
                    $weixin_data['country'] = $user_obj['country'];
                    $weixin_data['province'] = $user_obj['province'];
                    $weixin_data['language'] = $user_obj['language'];
                    $sex = $user_obj['sex'];
                } else {
                    echo 解析错误 ;exit;
                    $this->success('解析错误');
                }



                if ($openId) {
                    $is_weixin_exist = $GLOBALS['db']->getOne("SELECT count(*) FROM " . DB_PREFIX . "weixin_user WHERE openid='" . $openId."'");
                    if (empty($is_weixin_exist)) {
                        $weixin_rs = M("weixin_user")->add($weixin_data);
                    }
                    \es_session::set('wx_user_openid',$openId)  ;
                    wap_user_login( $openId);
                    $user_info = \es_session::get("user_info");
                    if($user_info['id'] > 0 ){
                        //header('Location:'.SITE_DOMAIN.'/index.php?m=home&c=uccenter&a=index');
                    }
                    if($user_info['id'] > 0 ){
                        $user_check_mobile_array = M("user")->where( 'wx_openid="'.$openId.'"')->find();
                        if($user_check_mobile_array['mobilepassed'] == 1){
                            header('Location:'.SITE_DOMAIN.'/index.php?m=home&c=uccenter&a=index&r='.$from);
                        }

                    }
                    //$_SESSION['user']['openid'] = $openId;
                    //$GLOBALS['wx_info']['openid'] = $_SESSION['user']['openid'];
                    /*$is_user_weixin_exist = $GLOBALS['db']->getOne( "SELECT count(*) FROM ".DB_PREFIX."user WHERE wx_openid=".$openId );
                    if(empty($is_user_weixin_exist)){
                        $weixin_rs = M("weixin_user")->add ($weixin_data);
                    }*/
                }

                //exit;
            }else{
                header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4a6d0b9fa17894ce&redirect_uri=http%3a%2f%2fwap.yzlicai.com%2findex.php%3fm%3dHome%26c%3dUserwxregister%26a%3dindex&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect');

            }

        }else{

            //插入微信user表
            $wx_rs = M('weixin_user')->where('openid="'.$openid_exist['wx_user_openid'].'"')->find();
            if(!$wx_rs){
                $openid_exist['openid'] = $openid_exist['wx_user_openid'] ;
                unset($openid_exist['wx_user_openid']);
                $user_obj = $openid_exist ;
                $weixin_rs = M("weixin_user")->add($openid_exist);
            }else{
                $user_obj = $openid_exist ;
                    wap_user_login( $openid_exist['wx_user_openid']);
                    $user_info = \es_session::get("user_info");
                    ///已经绑定手机号码
                    if($user_info['id'] > 0 ){
                        $user_check_mobile_array = M("user")->where( 'wx_openid="'.$openid_exist['wx_user_openid'].'"')->find();
                        if($user_check_mobile_array['mobilepassed'] == 1){
                            header('Location:'.SITE_DOMAIN.'/index.php?m=home&c=uccenter&a=index');
                        }
                    }
            }
            if(! \es_session::get('wx_user') ){
                echo '微信中断，请用其他方式登录。';

            }
		}

		$root['program_title']="绑定帐户" ;
        $this->assign('data',$root);
        $this->assign('wx_info',$user_obj);
        $root['is_login'] = $this->check_is_login() ;
		//output($root);
        $this->display();
	}

    //设置网络请求配置
    public function _request($curl,$https=true,$method='GET',$data=null){
        // 创建一个新cURL资源
        $ch = curl_init();

        // 设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $curl);    //要访问的网站
        curl_setopt($ch, CURLOPT_HEADER, false);    //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  //将curl_exec()获取的信息以字符串返回，而不是直接输出。

        if($https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //FALSE 禁止 cURL 验证对等证书（peer's certificate）。
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  //验证主机
        }
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_POST, true);  //发送 POST 请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  //全部数据使用HTTP协议中的 "POST" 操作来发送。
        }


        // 抓取URL并把它传递给浏览器
        $content = curl_exec($ch);
        if ($content  === false) {
            return "网络请求出错: " . curl_error($ch);
            exit();
        }
        //关闭cURL资源，并且释放系统资源
        curl_close($ch);

        return $content;
    }
    /**
     * 获取用户的openid
     * @param  string $openid [description]
     * @return [type]         [description]
     */
    public function baseAuth($redirect_url){

        //1.准备scope为snsapi_base网页授权页面
        $baseurl = urlencode($redirect_url);
        $snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YQJ#wechat_redirect';

        //2.静默授权,获取code
        //页面跳转至redirect_uri/?code=CODE&state=STATE
        $code = $_GET['code'];
        if( !isset($code) ){
            header('Location:'.$snsapi_base_url);
        }

        //3.通过code换取网页授权access_token和openid
        $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';
        $content = $this->_request($curl);
        $result = json_decode($content,true);

        return $result;
    }



}
?>
